package com.lai.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.lai.shop.constant.CommonConstant;
import com.lai.shop.entity.UserEntity;
import com.lai.shop.service.UserAuthService;
import com.lai.shop.service.UserService;
import com.lai.shop.vo.UserLoginVo;
import com.lai.shop.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;


@Controller
public class UserWebController {

    @Autowired
    UserService userService;

    @Autowired
    UserAuthService userAuthService;


    @GetMapping("/login")
    public String login(@Valid UserLoginVo userLoginVo, HttpSession session) {
        UserEntity user = userService.login(userLoginVo);
        if(ObjectUtil.isNotNull(user)){
            session.setAttribute(CommonConstant.LOGIN_USER,user);
            return "redirect:http://localhost:8099/index.html";
        }else{
            return "redirect:http://localhost:8099/login.html";
        }

    }

    @PostMapping("/register")
    public String register(UserRegisterVo userRegisterVo) {
        boolean resp = userService.register(userRegisterVo);
        if(resp){
            return "redirect:http://localhost:8099/login.html";
        }else{
            return "redirect:http://localhost:8099/register.html";
        }
    }

    @GetMapping("/oauth2.0/{platform}/auth")
    public String oauth2Login(@RequestParam("code") String code,@PathVariable("platform")String platform,HttpSession session){
        if("weibo".equals(platform)){
            UserEntity user = userAuthService.weiboLogin(code);
            if(ObjectUtil.isNotNull(user)){
                session.setAttribute(CommonConstant.LOGIN_USER,user);
                return "redirect:http://localhost:8099/index.html";
            }else{
                return "redirect:http://localhost:8099/login.html";
            }
        }else if("gitee".equals(platform)){
            UserEntity user = userAuthService.giteeLogin(code);
            if(ObjectUtil.isNotNull(user)){
                session.setAttribute(CommonConstant.LOGIN_USER,user);
                return "redirect:http://localhost:8099/index.html";
            }else{
                return "redirect:http://localhost:8099/login.html";
            }
        }
        return "login";
    }


    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(CommonConstant.LOGIN_USER);
        return "redirect:http://localhost:8099/login.html";
    }



}
